package com.study.forumsystemproject.controller;
import com.study.forumsystemproject.common.Result;
import com.study.forumsystemproject.common.ResultCode;
import com.study.forumsystemproject.exception.ApplicationException;
import com.study.forumsystemproject.model.Article;
import com.study.forumsystemproject.model.Board;
import com.study.forumsystemproject.model.PageInfo;
import com.study.forumsystemproject.model.ResultPage;
import com.study.forumsystemproject.service.impl.ArticleImpl;
import com.study.forumsystemproject.service.impl.BoardImpl;
import com.study.forumsystemproject.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Objects;

/**
 * program: forum-system-project
 * <p>
 * description: 文章控制层
 * <p>
 * author: xiaoxie
 * <p>
 * create: 2024-08-17 12:29
 **/
@RequestMapping("/article")
@RestController
@Slf4j
@Tag(name = "文章类测试API")
public class ArticleController {
    @Autowired
    private ArticleImpl articleImpl;
    @Autowired
    private BoardImpl boardImpl;
    @Operation(summary = "添加文章的API")
    @PostMapping("/add")
    public Result<Boolean> addArticle(@RequestBody Article article, HttpServletRequest request) {
        //校验参数
        Article.checkNullByArticle(article);
        //设置UserId
        String userTokenHeader = request.getHeader("user_token_header");
        Claims claims = JwtUtil.verifyJwt(userTokenHeader);
        if (claims == null) {
            log.warn("用户未登录");
           return Result.fail("用户未登录,请登录");
        }
        article.setUserId(((Number) claims.get("UserId")).longValue());
        articleImpl.addArticle(article);
        return Result.success(true);
    }
    @Operation(summary = "获取版块贴子的API")
    @PostMapping("/getList")
    public Result<PageInfo> getListByBoardId(Long boardId, @RequestBody ResultPage resultPage) {
        PageInfo pageInfo;
        if(boardId == null) {
            pageInfo = articleImpl.getAllArticles(resultPage);
        }else {
            pageInfo = articleImpl.getListByBoardId(boardId,resultPage);
        }

        return Result.success(pageInfo);
    }
    @Operation(summary = "获取版块信息的API")
    @GetMapping("/getBoard")
    public Result<Board> getBoardByBoardId(@NotNull Long boardId) {
        Board board = boardImpl.getBoardById(boardId);
        if(board == null) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            return Result.fail(ResultCode.FAILED_BOARD_NOT_EXISTS);
        }
        return Result.success(board);
    }
    @Operation(summary = "获取帖子详细信息的API")
    @GetMapping("/getDetails")
    public Result<Article> getDetailsByArticleId(HttpServletRequest request,@NotNull Long id) {
        Article article = articleImpl.selectDetailsByArticleId(request,id);
        if(article == null) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            return Result.fail(ResultCode.ERROR_SERVICES);
        }
        String userTokenHeader = request.getHeader("user_token_header");
        Claims claims = JwtUtil.verifyJwt(userTokenHeader);
        if (claims == null) {
            log.warn("用户未登录");
            return Result.fail("用户未登录,请登录");
        }
        Long userId = ((Number) claims.get("UserId")).longValue();
        if(Objects.equals(article.getUserId(), userId)) {
            article.setIsOwn(true);
        }
        return Result.success(article);
    }
    @Operation(summary = "更新帖子信息的API")
    @PostMapping("/modifyArticle")
    public Result<Boolean> modifyArticle(HttpServletRequest request, @Valid @RequestBody Article article) {
        //先通过id获取帖子信息
        Article articleById = articleImpl.getArticleById(article.getId());
        if(articleById == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return Result.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //校验该用户是否有权限修改该帖子
        Integer userState = (Integer) JwtUtil.getValue(request,"userState");
        if(userState == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return Result.fail(ResultCode.FAILED_USER_BANNED);
        }
        //校验帖子状态
        if(articleById.getState() == 1 || articleById.getDeleteFlag() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_STATE.toString());
            return Result.fail(ResultCode.FAILED_ARTICLE_NOT_STATE);
        }
        //开始修改
        articleImpl.modifyArticle(article.getId(), article.getTitle(),article.getContent());
        return Result.success(true);
    }
    @Operation(summary = "用户点赞的API")
    @PostMapping("/upvote")
    public Result<Boolean> upvoteArticle(HttpServletRequest request, @NotNull Long id) {
        Integer userState = (Integer) JwtUtil.getValue(request,"userState");
        if(userState == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return Result.fail(ResultCode.FAILED_USER_BANNED);
        }
        Boolean res = articleImpl.UpvoteByArticleId(request,id);
        //前端执行点赞的逻辑
        if(res) {
            return Result.success(true);
        }else{
            //前端执行取消点赞的逻辑
           return Result.success(false);
        }
    }
    @Operation(summary = "删除文章的API")
    @PostMapping("/delete")
    public Result deleteArticle(HttpServletRequest request, @NotNull Long id) {
        //校验用户状态
        Integer userState = (Integer) JwtUtil.getValue(request,"userState");
        if(userState == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return Result.fail(ResultCode.FAILED_USER_BANNED);
        }
        //校验用户是否为作者
       Long authorId = ((Number)JwtUtil.getValue(request,"UserId")).longValue();
        Article articleById = articleImpl.getArticleById(id);
        if(articleById == null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return Result.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(!Objects.equals(articleById.getUserId(), authorId)) {
            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
            return Result.fail(ResultCode.FAILED_UNAUTHORIZED);
        }
        //校验帖子状态
        if(articleById.getState() == 1 || articleById.getDeleteFlag() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_STATE.toString());
            return Result.fail(ResultCode.FAILED_ARTICLE_NOT_STATE);
        }
        //执行
        articleImpl.subArticle(id);
        log.info("删除帖子成功");
        return Result.success(true);
    }
    @Operation(summary = "通过UserId获取帖子列表的API")
    @PostMapping("/getArticleList")
    public Result<List<Article>> selectArticleByUserId(HttpServletRequest request, Long userId) {
        Long authorId = ((Number) JwtUtil.getValue(request,"UserId")).longValue();
        if(userId == null) {
            userId = authorId;
        }
        //执行查询
        List<Article> articles = articleImpl.selectDetailsByUserId(userId);
        return Result.success(articles);
    }
}
